/*
 Erica Sadun, http://ericasadun.com
 iPhone Developer's Cookbook, 3.0 Edition
 BSD License for anything not specifically marked as developed by a third party.
 Apple's code excluded.
 Use at your own risk
 */

#import <SystemConfiguration/SystemConfiguration.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <net/if.h>
#include <ifaddrs.h>
#import "UIDevice-Reachability.h"
#import <CoreTelephony/CTTelephonyNetworkInfo.h>
#import <CoreTelephony/CTCarrier.h>
#import "UIDevice-Helper.h"

#define ARRAY_SIZE(a) sizeof(a)/sizeof(a[0])

const char* jb_tool_pathes[] = {
    "/Applications/Cydia.app",
    "/Library/MobileSubstrate/MobileSubstrate.dylib",
    "/etc/apt"
};

@implementation UIDevice (Helper)

+ (BOOL)isFoundJBPath
{
    for (int i=0; i<ARRAY_SIZE(jb_tool_pathes); i++) {
        if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithUTF8String:jb_tool_pathes[i]]]) {
            NSLog(@"The device is jail broken!");
            return YES;
        }
    }
    NSLog(@"The device is NOT jail broken!");
    return NO;
}

+ (BOOL)isCanCallCydia
{
    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"cydia://"]]) {
        NSLog(@"The device is jail broken!");
        return YES;
    }
    NSLog(@"The device is NOT jail broken!");
    return NO;
}

#define USER_APP_PATH                 @"/User/Applications/"
#define USER_APP_PATH_IOS8            @"/User/Containers/Bundle/Application/"

+ (BOOL)isCanAccessUserAppPath
{
    if ([[NSFileManager defaultManager] fileExistsAtPath:USER_APP_PATH]) {
        NSLog(@"The device is jail broken!");
        //NSArray *applist = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:USER_APP_PATH error:nil];
        //NSLog(@"applist = %@", applist);
        return YES;
    }
    if ([UIDevice isIOS8OrLatter]){
        if ([[NSFileManager defaultManager] fileExistsAtPath:USER_APP_PATH_IOS8]) {
            NSLog(@"The device is jail broken!");
            //NSArray *applist = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:USER_APP_PATH error:nil];
            //NSLog(@"applist = %@", applist);
            return YES;
        }
    }
    
    NSLog(@"The device is NOT jail broken!");
    return NO;
}


+ (BOOL)isJBOS
{
#ifdef DEBUG
//    return YES;
#endif

    if ([UIDevice isCanAccessUserAppPath] && [UIDevice isCanCallCydia] && [UIDevice isFoundJBPath]){
        return YES;
    }
    return NO;
}  


@end

